#include"StringPool.h"
#include"variable.h"
#include"Alphabet.h"

Alphabet::Alphabet(){
	Map = HashMap();
	numEntries = 0;
	growthStopped = false;
}

Alphabet::Alphabet(int capacity){
	Map = HashMap(capacity);
	numEntries = 0;
	growthStopped = false;
}

Alphabet::~Alphabet(){
	HashMap::iterator iter;
	for(iter = Map.begin(); iter != Map.end(); ++iter){
		string* str = iter->first;
		pool->push_back(str);
	}
}

int Alphabet::lookupIndex(std::string* entry, bool &flag){
	if(entry == NULL){
		cout<<"Can't lookup \"null\" in an Alphabet."<<endl;
		system("pause");
	}

	int ret;
	HashMap::iterator iter = Map.find(entry);
	if(iter == Map.end()){
		ret = -1;
	}
	else{
		ret = iter->second;
	}
	flag = true;

	if(ret == -1 && !growthStopped){
		ret = numEntries;
		//printf("%s\n", entry->c_str());
		//system("pause");
		Map.insert(pair<string*, int>(entry, ret));
		numEntries++;
		flag = false;
	}

	return ret;
}

vector<string*>* Alphabet::toArray(){
	vector<string*>* v = new vector<string*>();
	HashMap::iterator iter;
	for(iter = Map.begin();iter != Map.end();iter++){
		string* str = iter->first;
		v->push_back(str);
	}
	return v;
}

bool Alphabet::contains(std::string *entry){
	return (Map.count(entry) == 0)?false:true;
}

int Alphabet::size(){
	return numEntries;
}

void Alphabet::stopGrowth(){
	growthStopped = true;
}

void Alphabet::allowGrowth() {
	growthStopped = false;
}

bool Alphabet::growthStop(){
	return growthStopped;
}

void Alphabet::writeObject(ObjectWriter &out){
	out.writeInt(CURRENT_SERIAL_VERSION);
	out.writeInt(numEntries);
	out.writeMap(Map);
	out.writeBool(growthStopped);
}

void Alphabet::readObject(ObjectReader &in){
	int version = in.readInt();
	numEntries = in.readInt();
	in.readMap(Map);
	growthStopped = in.readBool();
}

void Alphabet::display(){
	HashMap::iterator iter;
	for(iter = Map.begin();iter != Map.end();iter++){
		string* str = iter->first;
		int index = iter->second;
		cout<<str<<": "<<str->c_str()<<" ---> "<<index<<endl;
	}
	cout<<"----------------------------"<<endl;
}
